/**
 * @Author Yenchingcheng
 * @Date 2023/5/14 23:51
 * @Description 懒汉式
 **/
public class Singleton02 {

    public static void main(String[] args) {
        System.out.println("懒汉式：");
        //测试Singleton2
        Singleton2 s1 = Singleton2.getInstance();
        Singleton2 s2 = Singleton2.getInstance();
        System.out.println(s1 == s2);//返回true
        //测试Singleton3
        Singleton3 s3 = Singleton3.getInstance();
        Singleton3 s4 = Singleton3.getInstance();
        System.out.println(s3.hashCode() == s4.hashCode());//返回true
    }
}

//懒汉式（线程不安全）
class Singleton2 {

    //构造器私有化，不能new
    private Singleton2() {
    }

    //2.类内部创建静态对象实例
    private static Singleton2 instance;

    //3.提供共有的静态方法，返回实例对象，线程不安全
    public static Singleton2 getInstance() {
        //为空时才创建
        if (instance == null) {
            instance = new Singleton2();
        }
        return instance;
    }
}

//懒汉式（线程安全，同步方法）
class Singleton3 {
    //构造器私有化，不能new
    private Singleton3() {
    }

    //2.类内部创建静态对象实例
    private static Singleton3 instance;

    //3.提供共有的静态方法，返回实例对象,效率低
    public static synchronized Singleton3 getInstance() {
        //为空时才创建
        if (instance == null) {
            instance = new Singleton3();
        }
        return instance;
    }
}